import axios, {
  AxiosError,
  type AxiosResponse,
  type InternalAxiosRequestConfig,
} from "axios";
import { getToken, removeToken } from "./auth";

const request = axios.create({
  baseURL: "http://localhost:8080/",
  timeout: 10000,
});

//请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

//响应拦截
request.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data;
    if (res.code !== 200) {
      if (res.code === 401 || res.code === 403) {
        removeToken();
        window.location.href = "/login";
      }
      // 其他错误提示
      console.error("接口错误：", res.message);
      return Promise.reject(new Error(res.message || "请求失败"));
    }
    return res;
  },
  (error: AxiosError) => {
    // 网络错误或服务器异常
    if (error.response) {
      const status = error.response.status;
      if (status === 401) {
        removeToken();
        window.location.href = "/login";
      } else if (status >= 500) {
        console.error("服务器异常，请稍后再试");
      }
    } else {
      console.error("网络错误，请检查您的连接");
    }

    return Promise.reject(error);
  }
);

export default request;
